<?php
if ('game.php' == basename($_SERVER['SCRIPT_FILENAME']))
		die ('Please do not load this page directly. Thanks!');
   $msg= '';

	function nextquest($team_id){ //Сбросывает все записи из текущей в стат, а резал пишет данные следующего квеста
		    $query = "SELECT `poryadok`,`id`, `game_id` FROM `quests` WHERE `id`=(SELECT `cur_quest` FROM results WHERE `team_id` =".$team_id." LIMIT 1) LIMIT 1";
			$sqlporyadokindex = mysql_query($query) or die(mysql_error());
			if (mysql_num_rows($sqlporyadokindex)==1){
			$sqlporyadok = mysql_fetch_assoc($sqlporyadokindex);
			$sqlporyadok['poryadok']++;
			//echo "Игра идёт ".$sqlporyadok['game_id'];
			$query = "SELECT `id` FROM `quests` WHERE `game_id`=".$sqlporyadok['game_id']." AND `poryadok`={$sqlporyadok['poryadok']} LIMIT 1";

			$sqlporyadokindex = mysql_query($query) or die(mysql_error());
			        	if (mysql_num_rows($sqlporyadokindex)==1){

			        	$query="INSERT INTO stats SET
			        					`team_id` = {$team_id},
			        					`game_id` ={$sqlporyadok['game_id']},
			        					`quest_id` = {$sqlporyadok['id']}";
			    		//echo $query;
			    		mysql_query($query) or die (mysql_error());

						$sqlquestid = mysql_fetch_assoc($sqlporyadokindex);
						$query = "UPDATE results SET
									`cur_quest` = {$sqlquestid['id']},
									`team_id` = {$team_id},
									`quest_start` = NOW()";
						mysql_query($query) or die(mysql_error());
						}
                        else
                        {
                         echo 'Игра окончена (квесты кончились)!';
                         //Сообщить комманде что Усё, но саму игры не останавливать   
                        }
			}
	}

	$query = "SELECT code FROM codes WHERE `quest_id` = (SELECT `cur_quest` FROM results WHERE `team_id` =".$sqlteam['team_id']." LIMIT 1);";
   	$sqlcodes=mysql_query($query) or die(mysql_error());
    $query = "SELECT answer FROM answers WHERE `quest_id` = (SELECT `cur_quest` FROM results WHERE `team_id` =".$sqlteam['team_id']." LIMIT 1);";
   	$sqlanswers = mysql_query($query) or die(mysql_error());
   	echo "Кодов на задание ".mysql_num_rows($sqlcodes)."<br />";
   	echo "Принято кодов ".mysql_num_rows($sqlanswers)."<br />";
     if (mysql_num_rows($sqlcodes) == mysql_num_rows($sqlanswers)) {  //Задание закончено, оформляем переход на следующее
    	nextquest($sqlteam['team_id']);
	}


	if (isset($_GET['answer'])){
    $answer = mysql_escape_string($_GET['answer']);
    $query="SELECT * FROM `codes` WHERE `code` = '{$answer}' AND `quest_id` = (SELECT `cur_quest` FROM results WHERE `team_id` =".$sqlteam['team_id']." LIMIT 1) LIMIT 1";
	$sqlcodes = mysql_query($query) or die(mysql_error());
	      // $msg .=  "Начали проверку кодов!".mysql_num_rows($sqlcodes);
		if (mysql_num_rows($sqlcodes) == 1){
           $msg .=  "Код верный!";

            $query="SELECT * FROM `answers` WHERE `answer` = '{$answer}' AND `quest_id` = (SELECT `cur_quest` FROM results WHERE `team_id` =".$sqlteam['team_id']." LIMIT 1) LIMIT 1";
			$sqlcodes = mysql_query($query) or die(mysql_error());
           		 if (mysql_num_rows($sqlcodes) == 1){
            		$msg .= "Данный код уже принят!";
            	}

            	else{
            		//echo "Пишем код в таблицу с ответами";
            		$query="INSERT INTO answers
            		SET
            		 `quest_id`=(SELECT `cur_quest` FROM results WHERE `team_id` =".$sqlteam['team_id']." LIMIT 1),
            		 `team_id`={$sqlteam['team_id']},
            		 `answer`='{$answer}';";
            		  mysql_query($query) or die(mysql_error());
            		}

        }
			else{
			 $msg .= "Код не верный!";}
    }


function printquest($num){
	$query= "SELECT `poryadok`, `quest` FROM `quests` WHERE `id` = {$num}";
	$sqlindex=mysql_query($query) or die(mysql_error());
	$sqlarray = mysql_fetch_assoc($sqlindex);
	print "<p><b>Задание {$sqlarray['poryadok']}.</b></p>";
	print "<p>".$sqlarray['quest']."</p>";

	$query = "SELECT `hint` FROM `hints`,`results` WHERE `quest_id` = {$num} AND
 	(DATE_ADD(quest_start, INTERVAL `period` MINUTE) < NOW())";
	$sqlhintindex=mysql_query($query) or die(mysql_error());
		for ($i=1;$i <=  mysql_num_rows($sqlhintindex);$i++){
		$sqlhint=mysql_fetch_assoc($sqlhintindex);
		print "<b>Подсказонька ".$i."</b>";
		print "<p>".$sqlhint['hint']."</p>";
    }

	print "<p><i>
	Введите ответ:</i> <br /><input title=\"answer\" name=\"answer\" /> <br />
	</p>
	<do type=\"accept\" label=\"Послать\">
    <go href=\"index.php\" method=\"get\">
    <postfield name=\"pincode\" value=\"$(pincode)\" />
    <postfield name=\"answer\" value=\"$(answer)\" />
    </go>
	</do>";

}

$query = "SELECT
  			teams.team, application.game_id, application.team_id
			FROM
 			 application
 		 INNER JOIN teams ON application.team_id = teams.id
			WHERE application.pin = '{$_GET['pincode']}' LIMIT 1";
$sqlteamindex=mysql_query($query) or die(mysql_error());
$sqlteamarray = mysql_fetch_assoc($sqlteamindex);
  echo 'Игра команды "'.$sqlteamarray['team'].'"<br />';


$query = " SELECT `cur_quest` FROM `results` WHERE `team_id`={$sqlteamarray['team_id']} LIMIT 1";
$sqlresultindex = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($sqlresultindex)==1){
$sqlresultarray = mysql_fetch_assoc($sqlresultindex);



$query = "SELECT `time`,`quest_start` FROM `quests`,`results` WHERE `id` = {$sqlresultarray['cur_quest']} AND
 (DATE_ADD(quest_start, INTERVAL (SELECT `time` from quests WHERE `id`={$sqlresultarray['cur_quest']} LIMIT 1) MINUTE) < NOW()) LIMIT 1";
$sqltimeindex=mysql_query($query) or die(mysql_error());
if (mysql_num_rows($sqltimeindex)<1){printquest($sqlresultarray['cur_quest']);}
else {

	$query = "SELECT `poryadok` FROM `quests` WHERE `id`={$sqlresultarray['cur_quest']} LIMIT 1";
	$sqlporyadokindex = mysql_query($query) or die(mysql_error());
	if (mysql_num_rows($sqlporyadokindex)==1){
		$sqlporyadok = mysql_fetch_assoc($sqlporyadokindex);
		$sqlporyadok['poryadok']++;
		$query = "SELECT `id` FROM `quests` WHERE `game_id`={$sqlteamarray['game_id']} AND `poryadok`={$sqlporyadok['poryadok']} LIMIT 1";
		$sqlporyadokindex = mysql_query($query) or die(mysql_error());





        	if (mysql_num_rows($sqlporyadokindex)==1){
			$sqlquestid = mysql_fetch_assoc($sqlporyadokindex);
			$query = "UPDATE `results` SET
									`cur_quest` = {$sqlquestid['id']},
									`team_id` = {$sqlteamarray['team_id']},
									`quest_start` = NOW()";
			mysql_query($query) or die(mysql_error());



        	printquest($sqlquestid['id']);
        	}
        	else {print "Нибацца гамовер...";}
	}


//$sqlteamarray


} }
else {
	$query = "SELECT `id` FROM `quests` WHERE `game_id` = {$sqlteamarray['game_id']} AND `poryadok` = 1 LIMIT 1";
	$sqlquestindex=mysql_query($query) or die(mysql_error());
	$sqlquestarray = mysql_fetch_assoc($sqlquestindex);
	$query = "INSERT INTO `results` SET
									`cur_quest` = {$sqlquestarray['id']},
									`team_id` = {$sqlteamarray['team_id']},
									`quest_start` = NOW()";
	mysql_query($query) or die(mysql_error());

	printquest($sqlteamarray['team_id']);
	}


 echo $msg;


?>